﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketUtil
{
    public class SocketServer
    {
        private string _ip;
        public int _prot = 0;
        private Socket _socket = null;
        private byte[] buffer = new byte[1024 * 1024 * 2];

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip">监听的IP</param>
        /// <param name="port">监听的端口</param>
        public SocketServer(string ip,int port)
        {
            this._ip = ip;
            this._prot = port;
        }

        public SocketServer(int port)
        {
            this._ip = "0.0.0.0";
            this._prot = port;
        }

        public void StartListen()
        {
            try
            {
                //1. 实例化Socket IP4寻找协议,流式协议,TCP协议
                _socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                //2. 创建IP对象
                IPAddress address = IPAddress.Parse(_ip);

                //3.创建网络端口 ip和端口
                IPEndPoint endPoint = new IPEndPoint(address,_prot);

                //4. 绑定Socket
                _socket.Bind(endPoint);

                //5. 设置最大连接数
                _socket.Listen(int.MaxValue);

                Console.WriteLine($"监听{_socket.LocalEndPoint}消息成功");

                //6.开始监听
                Thread thread = new Thread(ListenClientConnect);
                thread.Start();
            }
            catch (Exception ex)
            {

            }

        }

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private void ListenClientConnect()
        {
            try
            {
                while(true)
                {
                    //Socket创建新的连接
                    Socket clientSoket = _socket.Accept();
                    clientSoket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));
                    Thread thread = new Thread(ReceiveMessage);
                    thread.Start(clientSoket);
                }


            }catch(Exception ex)
            {

            }
        }

        private void ReceiveMessage(object socket)
        {
            Socket clientsocket = (Socket)socket;

            while(true)
            {
                try
                {
                    //获取从客户端发来的数据
                    int length = clientsocket.Receive(buffer);

                    Console.WriteLine($"接受客户端{clientsocket.RemoteEndPoint},消息{Encoding.UTF8.GetString(buffer,0,length)}");

                }catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    clientsocket.Shutdown(SocketShutdown.Both);
                    clientsocket.Close();
                    break;
                }
            }

        }
    }
}
 